package com.bravo.mvpkotlin.ui.main

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bravo.mvpkotlin.R
import com.bravo.mvpkotlin.data.User
import com.bumptech.glide.Glide
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onClick

/**
 * Created by Administrator on 2017/6/24.
 */
class MainAdapter(val context: Context) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {

    var list:ArrayList<User> = arrayListOf()
    lateinit var onItemClickListener:OnItemClickListener

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        var user = list[position]
        Glide.with(context).load(user.avatar_url).into(holder?.userAvatar)
        holder?.user_name?.text = user.name
        holder?.user_scope?.text = "${user.score}"
        holder?.user_home?.text = user.html_url
        if (onItemClickListener != null){
            holder?.itemView?.onClick {
                onItemClickListener.onItemClick(user)
            }
        }
    }

    override fun getItemCount() = list.size

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(context).inflate(R.layout.adapter_user_item, parent, false)
        return ViewHolder(itemView)
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var userAvatar: ImageView = itemView.find(R.id.user_avatar)
        val user_name: TextView = itemView.find(R.id.user_name)
        val user_scope: TextView = itemView.find(R.id.user_scope)
        val user_home: TextView = itemView.find(R.id.user_home)
    }

    fun updateDatas(list: List<User>){
        this.list.clear()
        this.list.addAll(list)
        notifyDataSetChanged()
        Log.d("MainAdapter" , "数据加载完成。")
    }
    interface OnItemClickListener{
        fun  onItemClick(user: User)
    }
}

